package com
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import mx.collections.ArrayCollection;
	import mx.containers.VBox;
	import mx.controls.Alert;
	import mx.rpc.CallResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	
	
	//	[Bindable]
	public class DomainManager extends EventDispatcher
	{
		private var _valori:ArrayCollection;
		private var _domainsName:Array;
		[Bindable]
		private var _domainsValues:Array;
		//[Bindable]
		
		public function DomainManager(domainFile:String) {
			var my_req:URLRequest = new URLRequest(domainFile);
			var loader:URLLoader= new URLLoader(my_req);	
			loader.addEventListener(Event.COMPLETE,completeEventHandler);
			_domainsValues=new Array();
		}
		
		public function completeEventHandler(evt:Event):void {
			var dom:XML= XML(evt.target.data)
			
			for each (var dom1:XML in dom.domain) {
				if (!domainsValues[String(dom1.@id)]) {
					domainsValues[String(dom1.@id)]=new ArrayCollection();
				}	
				for each (var val:XML in dom1.value){
					var vObj:Object=new Object();
					vObj.label=String(val.@label);
					vObj.code=String(val.@id);
					if ((String(val.@default)=="") || (val.@default=="0"))  {
						vObj.default=false;
					}
						else {
							vObj.default=true;
						}
						
						if ((!String(val.@valid)=="")|| (val.@valid=="0"))
							vObj.valid="0";
						else
							vObj.valid="1";
						domainsValues[String(dom1.@id)].addItem (vObj);
						}
			}		
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		public function get domainsValues():Array
		{
			return _domainsValues;
		}
		//[Bindable]
		public function set domainsValues(value:Array):void
		{
			_domainsValues = value;
		}
		
		[Bindable(event="complete")] 
		public  function selectValue (domainName:String):ArrayCollection {
			return _domainsValues[domainName];
		}
		private function resultHandler (evt:ResultEvent) {
			_valori=evt.result as ArrayCollection;
			
			var dt:ArrayCollection=new ArrayCollection();
			for each ( var d:String in _domainsName) {
				_searchString=d
				dt=getValue(d);
				
				for each (var o:Object in dt)
				_domainsValues[d].addItem(o);
				
			}
			
		}
		private var _searchString:String
		public function getValue (domainName:String):ArrayCollection {
			return _domainsValues[domainName];
		}
		
		
		
		private function filterMyArrayCollection(item:Object):Boolean {
			
			var itemName:String = (item.id_dominio as String).toLowerCase();
			return itemName==_searchString;
		}
		
		
		
		private function faultHandler(evt:FaultEvent){
			Alert.show(evt.fault.faultString + '\n' + evt.fault.faultDetail);
		}
	}
}